package org.example.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Python脚本执行控制器
 *
 * @author rjs
 */
@RestController
public class PythonScriptController {

    private static final Logger logger = LoggerFactory.getLogger(PythonScriptController.class);

    /**
     * 执行Python脚本
     *
     * @param scriptPath 脚本路径
     * @param facePath   人脸文件路径
     * @param audioPath  音频文件路径
     * @param outputPath 输出文件路径
     * @return 执行结果
     */
    @GetMapping("/runscript")
    public String runPythonScript(@RequestParam String scriptPath, @RequestParam String facePath, @RequestParam String audioPath, @RequestParam String outputPath) {

        // 构建执行Python脚本的进程
        ProcessBuilder processBuilder = new ProcessBuilder("python", scriptPath, "--face", facePath, "--audio", audioPath, "--outfile", outputPath);
        processBuilder.inheritIO();

        try {

            // 启动进程执行脚本
            Process process = processBuilder.start();

            // 等待脚本执行完成,超时时间为2分钟
            boolean finished = process.waitFor(2, TimeUnit.MINUTES);

            // 检查脚本执行结果
            if (finished) {
                int exitCode = process.exitValue();
                if (exitCode == 0) {
                    return "执行成功";
                } else {
                    return "执行失败,退出代码 " + exitCode;
                }
            } else {
                // 超时后终止进程
                process.destroy();
                return "执行超时";
            }

        } catch (Exception e) {
            // 记录异常日志
            logger.error("执行脚本出错", e);
            return "脚本执行出错";
        }

    }

}


